package com.spring.demo.init.db;

import java.util.List;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;

import com.spring.demo.core.dao.mapper.MemberMapper;
import com.spring.demo.core.entity.Member;
import com.spring.demo.core.service.IMemberService;

@Configurable
@EnableTransactionManagement
@MapperScan("com.spring.demo.core.dao.mapper")
public class MybatisConfig extends EmbeddedDataSource {

	@Bean
	@Autowired
	public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();
		sessionFactoryBean.setDataSource(dataSource);
		sessionFactoryBean.setConfigLocation(new ClassPathResource(
				"/db/mybatis/mybatis-config.xml"));
		return sessionFactoryBean;
	}

	@Bean
	public IMemberService memberService() {
		return new MemberService();
	}

	@Bean
	@Autowired
	public PlatformTransactionManager transactionManager(DataSource dataSource) {
		DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
		transactionManager.setDataSource(dataSource);

		return transactionManager;
	}

	@Transactional
	static class MemberService implements IMemberService {
		@Autowired
		private MemberMapper memberMapper;

		@Override
		public void saveMember(Member member) {
			memberMapper.saveMember(member);
		}

		@Override
		public Member getMemberById(Long id) {
			return memberMapper.selectMember(id);
		}

		@Override
		public List<Member> getAllMembers() {
			return memberMapper.selectAllMember();
		}
	}
}